<?php
define('ROOT_PATH', dirname(__FILE__));
include(ROOT_PATH . '/eccore/ecmall.php');
require(ROOT_PATH . '/eccore/model/model.base.php');   //模型基础类
ecm_define(ROOT_PATH . '/data/config.inc.php');
ecm_define(ROOT_PATH . '/data/settings.inc.php');

include(ROOT_PATH . '/includes/global.lib.php');
include(ROOT_PATH . '/includes/libraries/time.lib.php');
include(ROOT_PATH . '/eccore/controller/app.base.php');
include(ROOT_PATH . '/includes/ecapp.base.php');
require(ROOT_PATH . '/app/frontend.base.php');
/* 环境 */
define('CHARSET', substr(LANG, 3));

/* 定义配置信息 */

try{
	$b=new BaseApp();
	$db =&db();
	$WX_APPID='wx6d434637b263c347';
	$WX_SECRET='6909b33a488b1d2bf5efaf58641613e4';
	$code=empty($_GET['code'])?"":$_GET['code'];
	if($code==""){
		$re = '{"access_token":"ACCESS_TOKEN","expires_in":7200,  "refresh_token":"REFRESH_TOKEN","openid":"123456","scope":"SCOPE"}';
	}
	else{
		$re = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token'."?appid=$WX_APPID&secret=$WX_SECRET&code=$code&grant_type=authorization_code");
	}
	$re = json_decode($re);
	if($re->errcode){
		$file = fopen("err_log.txt","w");
		fwrite($file,$re);
	}

	if($re->openid){
		setcookie('wxid',empty($re->openid)?"":$re->openid);

		if(!$_SESSION["user_info"]['user_id']){
			$mod_user =& m('member');

			$sql="select user_id, user_name, reg_time, last_login, last_ip from cw_member where weixin = '{$re->openid}'";
			$user_info=$db->getRow($sql);

			if ($user_info)
			{
				$_SESSION["user_info"]=$user_info;

				$wx='';
				try{
					$access_token=$re->access_token;

					if($access_token){
						$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$re->openid."&lang=zh_CN");

						$wx = json_decode($wx);
						if(property_exists($wx,"errcode")){
							$access_token=getAccessToken(true);

							if($access_token){
								$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=".$re->openid."&lang=zh_CN");
								$wx = json_decode($wx);
							}
						}
					}
				}
				catch(Exception $e){
					$file = fopen("err_log1.txt","w");
					fwrite($file,$e->getMessage());
				}

				if($wx){
					$sql = "update cw_member set headimgurl='$wx->headimgurl',real_name='$wx->nickname' where user_id=".$_SESSION["user_info"]['user_id'];
					$db->query($sql);
				}
				$file = fopen("info.txt","w");
				fwrite($file,$sql);

				$file = fopen("session.txt","w");
				fwrite($file,json_encode($_SESSION));
			}else{
				$wx='';
				try{
					$access_token=$re->access_token;

					if($access_token){
						$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$re->openid."&lang=zh_CN");

						$wx = json_decode($wx);
						if(property_exists($wx,"errcode")){
							$access_token=getAccessToken(true);

							if($access_token){
								$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=".$re->openid."&lang=zh_CN");
								$wx = json_decode($wx);
							}
						}
					}
				}
				catch(Exception $e){
					$file = fopen("err_log2.txt","w");
					fwrite($file,$re);
				}

				if($wx){
					$sql = "insert into cw_member set
					user_name='$re->openid',language='$wx->language',city='$wx->city',province='$wx->province',headimgurl='$wx->headimgurl',real_name='$wx->nickname'
					,status='关注',weixin='".$re->openid."',reg_time=".gmtime().",type='weixin'";
				}
				$db->query($sql);

				if($db->insert_id()){
					$sql="select user_id, user_name, reg_time, last_login, last_ip from cw_member where user_id = '".$_SESSION["user_info"]['user_id'];
					$user_info=$db->getRow($sql);

					if ($user_info)
					{
						$_SESSION["user_info"]=$user_info;
					}
				}
			}
		}else{
			$wx='';
			try{
				$access_token=$re->access_token;

				if($access_token){
					$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$re->openid."&lang=zh_CN");

					$wx = json_decode($wx);
					if(property_exists($wx,"errcode")){
						$access_token=getAccessToken(true);

						if($access_token){
							$wx=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=".$re->openid."&lang=zh_CN");
							$wx = json_decode($wx);
						}
					}
				}
			}
			catch(Exception $e){
				$file = fopen("err_log3.txt","w");
				fwrite($file,$re);
			}

			if($wx){
				$sql = "update cw_member set headimgurl='$wx->headimgurl',real_name='$wx->nickname' where user_id=".$_SESSION["user_info"]['user_id'];
			}
			$db->query($sql);
		}

		$url=$_GET['upp'];
		$u="";
		if(empty($url)){
			$u="index.php";
		}else{
			if(strpos($url,'|')>0){
				$u=explode('|', $url);
				$u=$u[0]."&".$u[1];
			}else{
				$u=$url;
			}
		}
		header("Location: $u");
	}
}
catch(Exception $e){
}

function getAccessToken($refresh=false){
	$access_token = null;
	$filename=ROOT_PATH . '/data/settings.inc.php';
	/* 载入配置项 */
	$settingconfig = include($filename);
	if(!$refresh&&$settingconfig["access_token"]){
		if($settingconfig["access_expires_in"]>=time()){
			$access_token = $settingconfig["access_token"];
		}
	}
	if(empty($access_token)){
		$WX_APPID='wx6d434637b263c347';
		$WX_SECRET='6909b33a488b1d2bf5efaf58641613e4';
		$re = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$WX_APPID&secret=$WX_SECRET");
		$re = json_decode($re);
		if(property_exists($re,"errcode")){
			throw new Exception($re->errcode);
		}
		if($re->access_token){
			$access_token = $re->access_token;
			$settingconfig["access_token"]=$re->access_token;
			$settingconfig["access_expires_in"]=time()+$re->expires_in-60;
			file_put_contents($filename, "<?php \nreturn " . var_export($settingconfig , true) . ";\n?>");
		}
	}
	return $access_token;
}